package org.cst.ming.android.barcode;


import java.util.Hashtable;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;


public class MainActivity
		extends Activity
{
	/** The SLF4J Logger. */
	private static final String TAG = "MainActivity";
	private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(TAG);

	private static final String PACKAGE = "com.google.zxing.client.android";
	private static final DialogInterface.OnClickListener EMPTY_DIALOG_ONCLICK_LISTENER = new DialogInterface.OnClickListener()
	{
		public void onClick(DialogInterface dialog, int which)
		{
		}
	};
	private static final Hashtable<EncodeHintType, String> DEFAULT_ENCODE_HINT = new Hashtable<EncodeHintType, String>();
	static
	{
		DEFAULT_ENCODE_HINT.put(EncodeHintType.CHARACTER_SET, "UTF8");
	}

	private int displayWidth = LayoutParams.FILL_PARENT;
	private int displayHeight = LayoutParams.FILL_PARENT;
	private int edgeLength = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		LOGGER.debug("onCreate");
		setContentView(R.layout.main);

		measureDisplaySize();

		findViewById(R.id.btnCallZXing).setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				// IntentIntegrator.initiateScan(MainActivity.this);
				Intent intentScan = new Intent(PACKAGE + ".SCAN");
				intentScan.setPackage(getPackageName());
				intentScan.addCategory(Intent.CATEGORY_DEFAULT);

				try
				{
					startActivityForResult(intentScan, IntentIntegrator.REQUEST_CODE);
				} catch (ActivityNotFoundException e)
				{
					final AlertDialog.Builder adBuilder = new AlertDialog.Builder(MainActivity.this);
					adBuilder.setMessage("Scan activity not found !");
					adBuilder.setPositiveButton("OK", EMPTY_DIALOG_ONCLICK_LISTENER);
					adBuilder.show();
				}
			}
		});

		findViewById(R.id.btnGenerateQRCode).setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				final AlertDialog.Builder adBuilder = new AlertDialog.Builder(MainActivity.this);
				final ViewGroup codeContentLayout =
						(ViewGroup) getLayoutInflater().inflate(R.layout.code_content_layout, null);
				final EditText textField = (EditText) codeContentLayout.findViewById(R.id.txfBarcodeContent);

				adBuilder.setView(codeContentLayout);
				adBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						final Dialog imageDialog = new Dialog(MainActivity.this, R.style.barcodeDisplayDialog);
						imageDialog.setContentView(R.layout.generated_code_layout);
						imageDialog.setCanceledOnTouchOutside(true);
						final ImageView barcodeImage = (ImageView) imageDialog.findViewById(R.id.imgBarcode);

						// generate QR-code
						try
						{
							final String content = textField.getText().toString();
							final BitMatrix bitMatrix =
									BarcodeWriter.encode(content, BarcodeFormat.QR_CODE, edgeLength, edgeLength, DEFAULT_ENCODE_HINT);
							barcodeImage.setImageBitmap(BarcodeWriter.toBitmap(bitMatrix));
						} catch (WriterException e)
						{
							LOGGER.warn("");
							barcodeImage.setBackgroundColor(Color.WHITE);
							barcodeImage.setLayoutParams(new RelativeLayout.LayoutParams(edgeLength, edgeLength));
						} catch (IllegalArgumentException e)
						{
							LOGGER.warn("");
							barcodeImage.setBackgroundColor(Color.WHITE);
							barcodeImage.setLayoutParams(new RelativeLayout.LayoutParams(edgeLength, edgeLength));
						}
						// generate end

						imageDialog.show();
					}
				});
				adBuilder.setNegativeButton("Cancel", EMPTY_DIALOG_ONCLICK_LISTENER);

				adBuilder.show();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);

		final IntentResult callResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
		final String rawBarcode = callResult.getContents();

		final TextView resultField = (TextView) findViewById(R.id.txtCallResultField);
		resultField.setText(rawBarcode);

		// send the message out.
		NetworkUtil.getUtil().send(rawBarcode);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		super.onConfigurationChanged(newConfig);
		measureDisplaySize();
	}

	private void measureDisplaySize()
	{
		final Display display = getWindowManager().getDefaultDisplay();
		displayWidth = display.getWidth();
		displayHeight = display.getHeight();
		edgeLength = (int) (Math.min(displayWidth, displayHeight) * 0.9);
	}
}
